package main

import (
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"strings"
)

func main() {
	fmt.Print("initServer......")
	initServer("", "8080")
}
func initServer(ip string, port string) {
	router := getRouter()
	err := http.ListenAndServe(":"+port, router)
	log.Println("start http server init")
	if err != nil {
		log.Fatalf("start http server failed, error: %s\n", err.Error())
	} else {
		log.Println("start http server success")
	}
}

/**
获取路由
*/
func getRouter() *http.ServeMux {
	mux := http.NewServeMux()
	mux.HandleFunc("/", index)
	mux.HandleFunc("/health", health)
	return mux
}

func index(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "welcome cloud primordial")
	setVersion(w)
	setHeader(w, r)
	ip := getCurrentIP(r)
	log.Printf("Success! Response code: %d", 200)
	log.Printf("Success! clientip: %s", ip)

}

/**
设置版本
*/
func setVersion(w http.ResponseWriter) {
	os.Setenv("VERSION", "v0.0.1")
	version := os.Getenv("VERSION")
	w.Header().Set("VERSION", version)
	log.Printf("os version: %s \n", version)
}

/**
设置响应头
*/
func setHeader(w http.ResponseWriter, r *http.Request) {
	for k, v := range r.Header {
		for _, vv := range v {
			log.Printf("Header key: %s, Header value: %s \n", k, v)
			w.Header().Set(k, vv)
		}
	}
}

/**
健康检查的路由
*/
func health(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "up")
}

/**
获取当前请求的ipi
*/
func getCurrentIP(r *http.Request) string {
	// 这里也可以通过X-Forwarded-For请求头的第一个值作为用户的ip
	//但是要注意的是这两个请求头代表的ip都有可能是伪造的
	ip := ClientIP(r)
	if ip == "" {
		// 当请求头不存在即不存在代理时直接获取ip
		ip = strings.Split(r.RemoteAddr, ":")[0]
	}
	return ip
}

// ClientIP 尽最大努力实现获取客户端 IP 的算法。
//解析 X-Real-IP 和 X-Forwarded-For 以便于反向代理（nginx 或 haproxy）可以正常工作。
func ClientIP(r *http.Request) string {
	xForwardedFor := r.Header.Get("X-Forwarded-For")
	ip := strings.TrimSpace(strings.Split(xForwardedFor, ",")[0])
	if ip != "" {
		return ip
	}
	ip = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
	if ip != "" {
		return ip
	}
	if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
		return ip
	}
	return ""
}
